package com.og.ouroa.handle;

import com.og.ouroa.common.annotations.EnableLoginHandle;
import com.og.ouroa.common.exception.Assert;
import com.og.ouroa.common.exception.BusinessException;
import com.og.ouroa.common.result.ResponseEnum;
import com.og.ouroa.utils.JwtUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.annotation.Annotation;

public class LoginHandle extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception
    {

        // 注解判断
        HandlerMethod method = (HandlerMethod) handler;
        EnableLoginHandle loginRequired = method.getMethodAnnotation(EnableLoginHandle.class);


        if (null == loginRequired)//未开启拦截
        {

            return true;
        } else //开启拦截
        {
            int identity = loginRequired.identity();
            String token = request.getHeader("token");  // 获取令牌(前端将token放入请求头中)
            boolean result = JwtUtils.checkToken(token);
            //拦截到未登录后直接抛异常,靠mvc的异常处理器去返回错误信息,要不然没办法返回错误信息
            Assert.isTrue(result, ResponseEnum.LOGIN_AUTH_ERROR);

             Boolean identity1 = JwtUtils.getIdentity(token);  //flase 为学生


                if(identity1){  //登录者是老师
                    return result;
                }else if                //登录者是学生
                (identity ==0 ) { //学生允许访问
                    return result;
                }else{  //登录者是学生 并且学生不允许访问
                    throw  new BusinessException("无权访问",-300);
                }



        }


    }

}
